package com.runen.infinitemovement.activity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.entity.ClockDetailsEntity;
import com.runen.infinitemovement.model.entity.PathFixedPointDetailEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by LiaoDuanHong
 * Create on 2020/09/17 10:09
 */
public class RoadLineDetailsActivity extends BaseActivity {
    @BindView(R.id.mzbView)
    MZBannerView mzbView;
    @BindView(R.id.tv_clock_point_name)
    TextView tvClockPointName;
    @BindView(R.id.tv_clock_introduce)
    TextView tvClockIntroduce;
    @BindView(R.id.tv_voice_time_of_long)
    TextView tvVoiceTimeOfLong;
    @BindView(R.id.ll_click_voice)
    LinearLayout llClickVoice;
    @BindView(R.id.tv_location_internet)
    TextView tvLocationInternet;
    @BindView(R.id.ll_internet)
    LinearLayout llInternet;
    @BindView(R.id.wb_clock_details)
    WebView wbClockDetails;
    @BindView(R.id.iv_media_player1)
    ImageView ivMediaPlayer1;
    @BindView(R.id.iv_media_player2)
    ImageView ivMediaPlayer2;
    @BindView(R.id.iv_media_player3)
    ImageView ivMediaPlayer3;
    @BindView(R.id.ll_mide)
    LinearLayout ll_mide;
    @BindView(R.id.ll_link)
    LinearLayout ll_link;
    @BindView(R.id.iv_player_btn)
    ImageView iv_player_btn;
    @BindView(R.id.ll_introduce)
    LinearLayout ll_introduce;
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_banner_num)
    TextView tvBannerNum;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;
    private String pathId;
    private String linkUrl;
    private String mediaPlayerUrl;
    private String voiceTime;
    private Boolean mapClickYanan = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_road_line_details;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("路线详情");
        pathId = getIntent().getStringExtra("pathId");
        mapClickYanan = getIntent().getBooleanExtra(ActivityCompat.MAP_CLICK_YANAN, false);
        mediaPlayer = new MediaPlayer();
        mzbView.setIndicatorVisible(false);
        initData();
    }

    private void initData() {
        if (mapClickYanan) {
            Map<String, Object> params = new HashMap<>();
            params.put("pointId", pathId);
            new ChallengeAPI().pathFixedPointDetail(params, new BaseResultCallback<PathFixedPointDetailEntity>() {
                @Override
                public void onResponse(PathFixedPointDetailEntity response) {
                    if (response.code == 0)
                        showView(response.data);
                }
            });
        } else {
            String str = "?pathSectionId=%s";
            new ChallengeAPI().roadSectionDetails(String.format(str, pathId), new BaseResultCallback<ClockDetailsEntity>() {
                @Override
                public void onResponse(ClockDetailsEntity response) {
                    if (response.code == 0) {
                        if (response.data != null) {
                            showView(response.data);
                        }
                    } else {
                        ToastUtils.showShort(response.msg);
                    }
                }
            });
        }
    }

    private void showView(PathFixedPointDetailEntity.DataBean response) {
        if (null != response) {
            if (!TextUtils.isEmpty(response.icon)) {
                GlideUtils.loadImage(RoadLineDetailsActivity.this, response.icon, iv_icon);
            }
            iv_icon.setVisibility(View.VISIBLE);
            mzbView.setVisibility(View.INVISIBLE);
            tvClockIntroduce.setVisibility(View.GONE);
            ll_mide.setVisibility(View.GONE);
            tvClockPointName.setText(response.fixedName);
            topTitle.setText(response.fixedName);
            if (TextUtils.isEmpty(response.introduction)) {
                ll_introduce.setVisibility(View.GONE);
            } else {
                ll_introduce.setVisibility(View.VISIBLE);
            }
            tvClockIntroduce.setText("本地详情");
            tvLocationInternet.setVisibility(View.GONE);

            ll_link.setVisibility(View.GONE);
            CommonUtil.loadData(response.detail, wbClockDetails);
        }
    }

    private void showView(ClockDetailsEntity.DataBean response) {
        if (null != response) {
            if (response.banners != null) {
                if (response.banners.size() > 0) {
                    tvBannerNum.setText((1) + "/" + response.banners.size());
                }
                mzbView.setPages(response.banners, new MZHolderCreator<BannerViewHolder>() {
                    @Override
                    public BannerViewHolder createViewHolder() {
                        return new BannerViewHolder(response.banners);
                    }
                });
                mzbView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        tvBannerNum.setText((position + 1) + "/" + response.banners.size());
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
            tvClockPointName.setText(response.startPoint + " - " + response.endPoint);
            if (TextUtils.isEmpty(response.introduction)) {
                ll_introduce.setVisibility(View.GONE);
            } else {
                ll_introduce.setVisibility(View.VISIBLE);
            }
            tvClockIntroduce.setText(response.introduction);
            tvLocationInternet.setText(response.linkName + "，点击进入");

            linkUrl = response.linkAddr;
//            mediaPlayerUrl = response.voiceUrl;
            if (!TextUtils.isEmpty(linkUrl)) {
                ll_link.setVisibility(View.VISIBLE);
            } else {
                ll_link.setVisibility(View.GONE);
            }
            mMediaPlayer();
            CommonUtil.loadData(response.content, wbClockDetails);
        }
    }


    public static class BannerViewHolder implements MZViewHolder<ClockDetailsEntity.DataBean.BannersBean> {
        private ImageView mImageView;
        private RelativeLayout rl_Video;
        private VideoView videoView;
        private ImageView im_click_play;
        private ImageView iv_videoView_bg;
        private List<ClockDetailsEntity.DataBean.BannersBean> listString = new ArrayList<>();

        public BannerViewHolder(List<ClockDetailsEntity.DataBean.BannersBean> lists) {
            listString.clear();
            for (int i = 0; i < lists.size(); i++) {
                listString.add(lists.get(i));
            }
        }

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.custom_mzb_bannar_view, null);
            mImageView = view.findViewById(R.id.iv_clock_details_bg);
            rl_Video = view.findViewById(R.id.rl_Video);
            videoView = view.findViewById(R.id.videoView);
            im_click_play = view.findViewById(R.id.im_click_play);
            iv_videoView_bg = view.findViewById(R.id.iv_videoView_bg);
            return view;
        }

        long pId;

        @Override
        public void onBind(final Context context, final int position, final ClockDetailsEntity.DataBean.BannersBean data) {
            if (data.bannerType == 0) {
                mImageView.setVisibility(View.VISIBLE);
                rl_Video.setVisibility(View.GONE);
                GlideUtils.loadImage(context, data.linkAddr, mImageView);
            } else {
                mImageView.setVisibility(View.GONE);
                rl_Video.setVisibility(View.VISIBLE);
                initVideoView(data.linkAddr, videoView, im_click_play, iv_videoView_bg);
            }
            im_click_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    videoView.start();
                    im_click_play.setVisibility(View.GONE);
                    iv_videoView_bg.setVisibility(View.GONE);
                }
            });
            rl_Video.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    videoView.pause();
                    im_click_play.setVisibility(View.VISIBLE);
                    iv_videoView_bg.setVisibility(View.VISIBLE);
                }
            });

        }
    }

    private static void initVideoView(String url, VideoView videoView, ImageView imClickPlay, ImageView iv_videoView_bg) {
        videoView.setVideoURI(Uri.parse(url));//设置视频文件
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //视频加载完成,准备好播放视频的回调
                videoView.start();
                iv_videoView_bg.setVisibility(View.GONE);
                imClickPlay.setVisibility(View.GONE);
            }
        });
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //视频播放完成后的回调
                imClickPlay.setVisibility(View.VISIBLE);
                iv_videoView_bg.setVisibility(View.VISIBLE);
//                videoView.canPause();
                videoView.stopPlayback();//停止播放视频,并且释放
                videoView.suspend();//在任何状态下释放媒体播放器
            }
        });
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //异常回调
                return false;//如果方法处理了错误，则为true；否则为false。返回false或根本没有OnErrorListener，将导致调用OnCompletionListener。
            }
        });
        videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                //信息回调
//                what 对应返回的值如下
//                public static final int MEDIA_INFO_UNKNOWN = 1;  媒体信息未知
//                public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 媒体信息视频跟踪滞后
//                public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; 媒体信息\视频渲染\开始
//                public static final int MEDIA_INFO_BUFFERING_START = 701; 媒体信息缓冲启动
//                public static final int MEDIA_INFO_BUFFERING_END = 702; 媒体信息缓冲结束
//                public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703; 媒体信息网络带宽（703）
//                public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 媒体-信息-坏-交错
//                public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 媒体信息找不到
//                public static final int MEDIA_INFO_METADATA_UPDATE = 802; 媒体信息元数据更新
//                public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901; 媒体信息不支持字幕
//                public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902; 媒体信息字幕超时

                return false; //如果方法处理了信息，则为true；如果没有，则为false。返回false或根本没有OnInfoListener，将导致丢弃该信息。
            }
        });
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return false;
    }

    @OnClick({R.id.top_btn_left, R.id.ll_click_voice, R.id.ll_internet})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;

            case R.id.ll_click_voice:
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.start();
                    handler.sendEmptyMessage(1);
                } else {
                    mediaPlayer.pause();
                    ivMediaPlayer1.setVisibility(View.GONE);
                    ivMediaPlayer2.setVisibility(View.GONE);
                    ivMediaPlayer3.setVisibility(View.GONE);
                    handler.removeMessages(1);
                    handler.removeMessages(2);
                    handler.removeMessages(3);
                    handler.removeMessages(4);
                }
                break;
            case R.id.ll_internet:
                if (!TextUtils.isEmpty(linkUrl)) {
                    Intent intent = new Intent(RoadLineDetailsActivity.this, WebActivity.class);
                    intent.putExtra("LINK_URL", linkUrl);
                    startActivity(intent);
                }
                break;
        }
    }

    private MediaPlayer mediaPlayer;

    private void mMediaPlayer() {
        try {
            if (!TextUtils.isEmpty(mediaPlayerUrl)) {
                ll_mide.setVisibility(View.VISIBLE);
                mediaPlayer.setDataSource(mediaPlayerUrl);
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
//                    mp.start();
                    }
                });
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        handler.removeMessages(1);
                        handler.removeMessages(2);
                        handler.removeMessages(3);
                        handler.removeMessages(4);
                    }
                });
            } else {
                ll_mide.setVisibility(View.GONE);
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
//                    iv_player_btn.setVisibility(View.VISIBLE);
                    GlideUtils.loadImage(RoadLineDetailsActivity.this, CommonUtil.getDrawable(R.mipmap.ico_saying1), iv_player_btn);
                    handler.sendEmptyMessageDelayed(2, 500);
                    break;
                case 2:
//                    iv_player_btn.setVisibility(View.VISIBLE);
                    GlideUtils.loadImage(RoadLineDetailsActivity.this, CommonUtil.getDrawable(R.mipmap.ico_saying2), iv_player_btn);
                    handler.sendEmptyMessageDelayed(3, 500);
                    break;
                case 3:
                    GlideUtils.loadImage(RoadLineDetailsActivity.this, CommonUtil.getDrawable(R.mipmap.ico_saying), iv_player_btn);
                    handler.sendEmptyMessageDelayed(4, 500);
                    break;
                case 4:
//                    iv_player_btn.setVisibility(View.INVISIBLE);
//                    iv_player_btn.setVisibility(View.INVISIBLE);
//                    iv_player_btn.setVisibility(View.INVISIBLE);
                    handler.sendEmptyMessageDelayed(1, 500);
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        handler.removeMessages(1);
        handler.removeMessages(2);
        handler.removeMessages(3);
        handler.removeMessages(4);
    }
}
